<template>
  <!-- 商品列表 -->
  <div class="sort-list-container">
    <ul>
      <li v-for="good in goodList" :key="good.id">
        <GoodsItem :good="good" />
      </li>
    </ul>
  </div>
  <!-- 上拉加载更多组件 -->
  <XtxInfiniteLoad
    :isLoading="isLoading"
    :isFinished="isFinished"
    @load="getNextPage"
  />
</template>

<script>
import GoodsItem from './goods-item.vue'
import { findSubCategoryGoods } from '@/api/category'
import { useRoute } from 'vue-router'
import { ref, watch, inject } from 'vue'
// 抽离列表渲染数据和逻辑
function useList (filterParams) {
  const goodList = ref([])
  // 列表请求的参数=> 不参与模板渲染，定义为普通的js数据
  const route = useRoute()
  const requestParams = {
    page: 0,
    pageSize: 20,
    categoryId: route.params.id,
    sortField: null, // 排序类别
    attrs: [], // 商品属性
    brandId: null // 品牌名称
  }
  // 实现上拉加载更多
  const isLoading = ref(false)
  const isFinished = ref(false)
  // 下拉加载更多回调函数
  const getNextPage = async () => {
    /**
       * 1. 开启列表加载，显示loading=》isLoading=true
       * 2. 发请求获取列表数据=》每次请求之前页码加一
       * 3. 获取到数据后追加到列表
       * 4. 关闭加载状态，隐藏loading=》isLoading=false
       * 5. 判断列表数据是否加载完了 =》根据list长度和后台total对比=》如果加载完=》isFinished = true
       */
    isLoading.value = true
    requestParams.page++
    const { result: { items, counts } } = await findSubCategoryGoods({ ...requestParams, ...filterParams.value })
    goodList.value.push(...items)
    isLoading.value = false
    if (goodList.value.length === counts) {
      isFinished.value = true
    }
  }

  return { goodList, requestParams, isLoading, isFinished, getNextPage }
}
export default {
  components: {
    GoodsItem
  },
  setup () {
    // 接收过滤条件数据
    const filterParams = inject('filterParams')
    // 处理列表渲染钩子函数
    const { goodList, requestParams, isLoading, isFinished, getNextPage } = useList(filterParams)

    // 重点：监听filterParams的变化=》如果变化刷新列表
    watch(() => filterParams.value, () => {
      console.log('过滤条件变化了：', filterParams.value)
      // 重置列表
      // 删除列表数据
      goodList.value = []
      // 重置数据请求状态
      requestParams.page = 0
      isLoading.value = false
      isFinished.value = false
      // getGoodList()
    }, { deep: true })

    return { goodList, isLoading, isFinished, getNextPage }
  }
}
</script>

<style lang="less" scoped>
.sort-list-container {
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
